<template>
  <div class="bigbox">
    <div class="common-header">
      <div class="pageTitle">低成本晾晒档案</div>
      <div>
        <el-button type="primary" size="small" @click="exp">导出模板</el-button>
        <el-button type="primary" size="small" @click="edit">编辑</el-button>
      </div>
    </div>
    <div style="margin: 20px; margin-top: 60px">
      <LowerCommon :columns="tableColumn" />
    </div>
    <!-- 不展示，只是用来导出数据 -->
    <div style="position: fixed; left: -10000px; width: 100%">
      <vxe-table
        ref="table"
        resizable
        show-header-overflow
        align="center"
        :data="tableData"
        border
        :merge-cells="mergeCells"
      >
        <vxe-column type="seq" title="序号" width="60" show-overflow></vxe-column>
        <vxe-column field="airDryingSubcategory" title="晾晒子目" width="120" show-overflow></vxe-column>
        <vxe-column field="evaluationMode" title="考核晾晒方式" show-overflow></vxe-column>
        <vxe-column field="assessmentInstructions" title="考核晾晒说明" show-overflow></vxe-column>
        <vxe-column field="computationalFormula" title="计算公式" show-overflow></vxe-column>
        <vxe-column field="unit" title="单位" width="80" show-overflow></vxe-column>
        <vxe-column field="dept" title="牵头责任部门">
          <template #default="{ row }">
            <div class="deptBox">
              <!-- <p v-for="name in row.dept ? row.dept.split(',') : []" :key="name" class="label">
                {{ name }}
              </p> -->
              <p>{{ typeof row.dept === 'string' ? row.dept.replaceAll(',', '\r\n') : row.dept }}</p>
            </div>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
  </div>
</template>
<script>
import LowerCommon from './common';
export default {
  components: { LowerCommon },
  data() {
    return {
      tableColumn: [
        //         {
        //           width: 60,
        //           slots: {
        //             default: () => {
        //               return [
        //                 <span class="drag-btn">
        //                   <i class="vxe-icon-menu"></i>
        //                 </span>,
        //               ];
        //             },
        //             header: () => {
        //               return [
        //                 <vxe-tooltip v-model={this.showHelpTip2} content="按住后可以上下拖动排序！" enterable>
        //                   <i
        //                     class="vxe-icon-question-circle-fill"
        //                     onClick={() => {
        //                       this.showHelpTip2 = !this.showHelpTip2;
        //                     }}
        //                   ></i>
        //                 </vxe-tooltip>,
        //               ];
        //             },
        //           },
        //         },
        {
          field: 'evaluationMode',
          treeNode: true,
          title: '晾晒子目/考核晾晒方式',
          editRender: {},
          slots: {
            default: 'airDryingSubcategory_default',
          },
        },
        {
          field: 'assessmentInstructions',
          title: '考核晾晒说明',
          editRender: {},
          slots: { default: 'assessmentInstructions_default' },
        },
        {
          field: 'unit',
          title: '单位',
          width: 80,
          editRender: {},
          slots: { default: 'unit_default' },
        },
        //         {
        //           field: 'lineNumber',
        //           title: '行号',
        //           editRender: {},
        //           slots: { edit: 'lineNumber_edit', default: 'lineNumber_default' },
        //         },
        {
          field: 'operationField',
          title: '对应项目运营字段',
          editRender: {},
          slots: { default: 'operationField_default' },
        },
        {
          field: 'dept',
          title: '牵头责任部门',
          editRender: {},
          slots: { default: 'dept_default' },
        },
      ],
      tableData: [],
      mergeCells: [],
    };
  },
  async created() {
    await this.getExport();
  },
  methods: {
    edit() {
      this.$router.push('/lowcostEdit');
    },
    async getExport() {
      await this.$api
        .ApiLowcostPageList({
          enabledFlag: true,
          page: 0,
          size: 1000,
        })
        .then((res) => {
          try {
            function flatten(arr = []) {
              return arr.reduce(function (prev, item) {
                if (!item.children || item.children.length === 0) {
                  return prev.concat({
                    ...item,
                  });
                } else {
                  return prev.concat(
                    flatten(
                      item.children.map((it) => {
                        return {
                          ...it,
                          airDryingSubcategory: item.airDryingSubcategory,
                          dept: item.dept,
                        };
                      }) || [],
                    ),
                  );
                }
              }, []);
            }
            this.tableData = this.tranform(flatten(res.list));
          } catch {}
        });
    },
    tranform(table) {
      const transformRow = (list, column = 1, row = 0) => {
        let start = 0;
        while (start < list.length) {
          const first = list[start];
          const last = list.lastIndexOf(first);
          if (start !== last) {
            this.mergeCells.push({
              row: start + row,
              col: column,
              rowspan: last - start + 1,
              colspan: 1,
            });
          }
          start = last + 1;
        }
      };
      const airDryingSubcategorys = table.flat(1).map((item) => item.airDryingSubcategory);
      transformRow(airDryingSubcategorys, 1);
      let prevParentId = null;
      const prev = table.flat(1).reduce((prev, cur) => {
        if (prevParentId !== cur.parentId) {
          prevParentId = cur.parentId;
          prev.push([cur]);
        } else {
          prev[prev.length - 1].push(cur);
        }
        return prev;
      }, []);
      let i = 0;
      prev.forEach((list) => {
        const depts = list.map((item) => item.dept);
        transformRow(depts, 6, i);
        i += depts.length;
      });
      return table.flat(1);
    },
    exp() {
      const fixedRow = 1;
      this.$refs.table.exportData({
        filename: '低成本晾晒表',
        sheetName: '低成本晾晒表',
        type: 'xlsx',
        useStyle: true,
        columnFilterMethod: (column, $columnIndex) => {
          return !(column.$columnIndex === 0);
        },
        sheetMethod: ({ options, workbook, worksheet }) => {
          // 插入标题
          worksheet.insertRow(1, ['低成本晾晒表']);
          worksheet.mergeCells(1, 1, 1, 6);
          const fixedIndex = 1;
          this.mergeCells.forEach((mergeCell) => {
            const { row, col, rowspan, colspan } = mergeCell;
            worksheet.mergeCells(
              row + fixedRow + fixedIndex + 1,
              col,
              row + rowspan + fixedIndex + 1,
              col + colspan - 1,
            );
          });
          // 设置所有单元格
          worksheet.eachRow((row) => {
            row._cells.forEach((item) => {
              item.border = {
                top: { style: 'thin', color: { argb: '000000' } },
                left: { style: 'thin', color: { argb: '000000' } },
                bottom: { style: 'thin', color: { argb: '000000' } },
                right: { style: 'thin', color: { argb: '000000' } },
              };
            });
            row.eachCell((cell) => {
              //设置单元格样式
              cell.fill = {
                type: 'pattern',
                pattern: 'thin',
                fgColor: { argb: 'FF000000' },
              };
              cell.font = { color: { argb: 'FF000000' } };
              // 设置自动换行
              cell.alignment = { wrapText: true, vertical: 'middle', horizontal: 'center', indent: 1 };
            });
          });
        },
      });
    },
  },
};
</script>
<style lang="scss" scoped>
</style>

